<template>
    <n-data-table :columns="columns" :row-key="(row:any)=>row[key||'id']" v-bind="$attrs" :data="list" :flex-height="true" class="flex-1"  @update:sorter="handleSorterChange" />
    <div class="mt-xs w-full" v-if="pageObj">
        <n-pagination class="justify-center" v-model:page="pageObj.current" v-model:page-size="pageObj.size"
            :item-count="pageObj.total" show-size-picker :page-sizes="[10, 20, 30, 50, 100]"
            @update:page="handlePageUpdate" @update:page-size="handlePageSizeUpdate" >
						<template #prefix="{ itemCount }">
							共 {{ itemCount }} 行
						</template>
		</n-pagination>
    </div>
</template>

<script  setup lang='ts' >
import { DataTableColumn, DataTableSortState} from 'naive-ui';


const emit = defineEmits(['pageUpdate'])

type Props = {
    list:any[],columns:DataTableColumn<any>[],pageObj?:Common.Page<any> ,key?:string
}
const { list,columns,pageObj } = defineProps<Props>()
function handlePageUpdate(page: number){
	if(pageObj)
		pageObj.current = page
  emit("pageUpdate",page,pageObj!.size)
}
function handlePageSizeUpdate(pageSize: number){
	if(pageObj){
		pageObj.size = pageSize
		pageObj.current = 1
	}
  emit("pageUpdate",1,pageSize)
}
function handleSorterChange(options: DataTableSortState | DataTableSortState[] | null){
	if(!pageObj)return;
	if(options){
		if(options instanceof Array){
			let orderItems = options.map(it=>{
				return {column:toUnderline(it.columnKey),asc:it.order=='ascend'} as Common.PageOrderItem
			})
			pageObj.orders = orderItems
		}else{
			pageObj.orders = [{column:toUnderline(options.columnKey),asc:options.order=='ascend'} ]
		}
	}else{
		pageObj.orders = undefined
	}
	emit("pageUpdate",pageObj.current,pageObj.size,pageObj.orders)
}

/**
 * 将驼峰变成下划线
 * @param str  需要变化的字符串
 */
function toUnderline(str:string|number):string {
		const temp = str + ''
		return temp.replace(/([A-Z])/g, '_$1').toLowerCase();
	}

defineOptions({ name: 'SDataTable' });
</script>

<style lang='scss' scoped>
</style>
